package config

import (
	"fmt"
	"github.com/spf13/viper"
	"os"
)

type Config struct {
	Server struct {
		Http      int `mapstructure:"http"`
		Websocket int `mapstructure:"websocket"`
		Latency   int `mapstructure:"latency"`
	} `mapstructure:"server"`
	Database Database `mapstructure:"database"`

	Redis struct {
		URL      string   `mapstructure:"url"`
		Servers  []string `mapstructure:"servers"`
		PoolSize int      `mapstructure:"pool_size"`
		Password string   `mapstructure:"password"`
		Database int      `mapstructure:"database"`
	} `mapstructure:"redis"`
}

type Database struct {
	Type     string `mapstructure:"type"`
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	User     string `mapstructure:"user"`
	Password string `mapstructure:"password"`
	Name     string `mapstructure:"name"`
}

var Cfg Config

// 用path是方便写test用例
func init() {
	v := viper.New()

	v.SetConfigName("config")
	v.SetConfigType("yml")
	v.AddConfigPath(".")
	err := v.ReadInConfig()
	if err != nil {
		fmt.Println("read config error: " + err.Error())
		os.Exit(1)
	}
	err = v.Unmarshal(&Cfg)
	if err != nil {
		fmt.Println("unmarshal config error: " + err.Error())
		os.Exit(1)
	}
}

func (d Database) GenerateMysqlDsn() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
		d.User, d.Password, d.Host, d.Port, d.Name,
	)
}
